import { observable, action, makeObservable, configure, computed } from 'mobx'

configure({
  enforceActions: 'observed',
})

const defaultUser = {
  id: '',
  token: '',
  username: '',
  password: '',
}

class UserStore {
  constructor() {
    makeObservable(this, {
      user: observable,
      isLogin: computed,
      login: action,
    })
  }

  user = defaultUser
  initUser = false

  login(nUser) {
    this.initUser = true
    if (!nUser) return
    this.user = nUser
    if (nUser.token) {
      localStorage.setItem('user', JSON.stringify(nUser))
    }
  }

  logout() {
    this.user = { ...defaultUser }
    this.initUser = true
    localStorage.removeItem('user')
  }

  get isLogin() {
    if (this.user.token) {
      return true
    }
    return false
  }
}

const userStore = new UserStore()

export default userStore
